package com.xu.common.mail.impl;

import cn.hutool.core.util.StrUtil;
import com.xu.common.exception.MyException;
import com.xu.common.mail.MailDTO;
import com.xu.common.mail.MailService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;
import java.util.concurrent.CompletableFuture;

/**
 * 邮件实现类
 *
 * @author xu
 * 2021/8/23 13:00
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Resource
    private JavaMailSenderImpl mailSender;//注入邮件工具类

    @Override
    public CompletableFuture<Boolean> sendMail(MailDTO mailDTO) {
        try {
            checkMail(mailDTO); //1.检测邮件
            sendMimeMail(mailDTO); //2.发送邮件
            return CompletableFuture.completedFuture(true);
        } catch (Exception e) {
            return CompletableFuture.completedFuture(false);
        }
    }

    //检测邮件信息类
    private void checkMail(MailDTO mailDTO) {
        if (StrUtil.isEmpty(mailDTO.getToUser())) {
            throw new MyException("邮件收信人不能为空");
        }
        if (StrUtil.isEmpty(mailDTO.getSubject())) {
            throw new MyException("邮件主题不能为空");
        }
        if (StrUtil.isEmpty(mailDTO.getText())) {
            throw new MyException("邮件内容不能为空");
        }
    }

    //构建复杂邮件信息类
    private void sendMimeMail(MailDTO mailDTO) {
        try {
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailSender.createMimeMessage(), true);//true表示支持复杂类型
            messageHelper.setFrom(mailDTO.getFromUser());//邮件发信人
            messageHelper.setTo(mailDTO.getToUser().split(","));//邮件收信人
            messageHelper.setSubject(mailDTO.getSubject());//邮件主题
            messageHelper.setText(mailDTO.getText());//邮件内容
            if (!StrUtil.isEmpty(mailDTO.getCc())) {//抄送
                messageHelper.setCc(mailDTO.getCc().split(","));
            }
            if (!StrUtil.isEmpty(mailDTO.getBcc())) {//密送
                messageHelper.setCc(mailDTO.getBcc().split(","));
            }
            if (mailDTO.getMultipartFiles() != null) {//添加邮件附件
                for (MultipartFile multipartFile : mailDTO.getMultipartFiles()) {
                    messageHelper.addAttachment(Objects.requireNonNull(multipartFile.getOriginalFilename()), multipartFile);
                }
            }
            if (null != mailDTO.getSentDate()) {//发送时间
                mailDTO.setSentDate(new Date());
                messageHelper.setSentDate(mailDTO.getSentDate());
            }
            mailSender.send(messageHelper.getMimeMessage());//正式发送邮件
            mailDTO.setStatus("ok");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);//发送失败
        }
    }
}

